import axios from 'axios'
import { MessageBox, Message, Loading } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
var loading = null
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    withCredentials: false, // send cookies when cross-domain requests
    timeout: 10000 // request timeout
})
service.interceptors.request.use(
    config => {
        if (!getToken()) {
            pending = []
        }
        config['Content-Type'] = 'application/x-www-form-urlencoded'
        loading = Loading.service({
            lock: true,
            text: '',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
        })
        return config
    },
    error => {
        return Promise.reject(error)
    }
)
service.interceptors.response.use(
    response => {
        setTimeout(() => {
            loading.close()
        })
        const res = response.data
        if (res.code !== '0') {
            MessageBox.confirm(res.msg || 'Error', '提示', { dangerouslyUseHTMLString: true, type: 'warning' }, {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {})
            return Promise.reject(new Error(res.msg || 'Error'))
        } else {
            return res
        }
    },
    error => {
        const resp = error.response
        loading.close()
        if (error.response.status === 426) {
            Message({
                message: resp.data.msg || resp.msg,
                type: 'error',
                duration: 5 * 1000
            })
        } else if (error.response.status === 401) {
            Message({
                message: error.msg || resp.data.msg,
                type: 'error',
                duration: 5 * 1000
            })
            store.dispatch('user/resetToken').then(() => {
                location.reload()
            })
        } else if (resp.data.msg === '服务器异常, 请稍后再试！') {
            Message({
                message: '系统发生未知错误，请联系技术部门处理！',
                type: 'error',
                duration: 5 * 1000
            })
        } else {
            Message({
                message: error.msg || resp.data.msg || '网站访问异常，请检查您的网络设置！',
                type: 'error',
                duration: 5 * 1000
            })
        }
        return Promise.reject(error)
    }

)

export default service
